<script src="./static/vue.min.js"></script>
<script src="./static/vuex.js"></script>
<div id="app">
<div>
<h4>{{ name }}</h4> <!-- name 只会去调取computed 里的数据-->
</div>
</div>
<script>
Vue.use(Vuex);
let store = new Vuex.Store({
state: {
name: 'wqp',
},
})
new Vue({
el: "#app",
store: store,
computed: {
name: function () {
console.log(this);
return this.$store.state.name; // 想获取到vuex中的store数据,只能在这里获取
}
}
})
</script>
<div id="app">
<div>
<h2>{{ age }}</h2> <!-- age 只会去调取computed 里的数据-->
</div>
</div>
<script>
Vue.use(Vuex);
let store = new Vuex.Store({
state: {
age: 10
},
getters: {
getAge: function (state) {
return state.age + 20 // 调取 state的值
}
}
})
new Vue({
el: "#app",
store: store,
computed: {
age: function() {
console.log(this)
return this.$store.getters.getAge; // 调取 getters 里定义的方法
}
}
})
</script>
<div id="app">
<div>
<h4>{{ score }}</h4>
<button @click="changeScore">修改成绩</button>
</div>
</div>
<script>
Vue.use(Vuex);
let store = new Vuex.Store({
state: {
score: 100
},
mutations: {
changeScore: function (state, payload) {
console.log('payload: ', payload)
return state.score += payload // 修改数据变量
}
}
})
new Vue({
el: '#app',
store: store,
computed: {
score: function() {
return this.$store.state.score
}
},
methods: {
changeScore: function() {
this.$store.commit("changeScore", 555) // 触发变更操作,会调取 mutations 里定义的“changeScore” 方法
}
}
})
</script>
<div id="app">
<div>
<h4>{{ score }}</h4>
<button @click="reduceScore">点击减少成绩</button>
</div>
</div>
<script>
Vue.use(Vuex);
let store = new Vuex.Store({
state: {
score: 100
},
mutations: {
reduceChangeScore: function(state, payload) {
return state.score -= payload
}
},
actions: {
reduceActionsScore: function(content, payload) {
console.log("content: ", content)
content.commit("reduceChangeScore", payload) // 实际上还是调取 mutations 里的方法
}
}
})
new Vue({
el: "#app",
store: store,
computed: {
score: function () {
return this.$store.state.score
}
},
methods: {
reduceScore: function () {
this.$store.dispatch("reduceActionsScore", 10); // 调取actins里定义的方法
}
}
})
</script>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。