vuex如何修改状态state的方法 |
vuex修改状态state方法vuex想要改变state里的属性,官方推荐的方法是通过mutaion的方式修改state 。 例如: store.js const state = {
num:0
}
const mutations = {
SET_NUM(state, payload) {
state.num= payload;
},
}
export default new Vuex.Store({
state,
mutations
})<template>
...
</template>
<script>
export default{
data(){
return{
num:1
}
},
methods:{
doSomething(){
this.$store.commit('SET_NUM',this.num);
}
}
}
</script>在组件里直接修改state也是生效的,例如: doSomething(){
this.$store.state.num = this.num;
} 但是不推荐这种直接修改state的方式,因为这样不能使用vuex的浏览器插件来跟踪状态的变化,不利于调试 。
vuex state使用/教程/实例说明
官网
state概述单一状态树
响应式 state存放的数据是响应式的:如果store的数据改变,依赖这个数据的组件也会更新 。 用法直接使用 // 在JS中使用 this.$store.state.变量名 // 不分模块 this.$store.state.模块名.变量名 // 分模块//在模板上使用 $store.state.变量名 // 不分模块 $store.state.模块名.变量名 // 分模块 mapState import { mapState } from 'vuex'
export default {
computed: {
...mapState(['state属性名']) // 不分模块,不修改属性名
...mapState({'新属性名称':'state属性名'}) // 不分模块,修改属性名
...mapState('模块名', ['state属性名']) // 分模块,不修改属性名
}
}示例代码 CouterStore.js import Vue from 'vue';
import Vuex from 'vuex';Vue.use(Vuex);
const counterStore = new Vuex.Store(
{
state: {
count: 10
},
}
);export default counterStore;Parent.vue <template>
<div class="outer">
<h3>父组件</h3>
<component-b></component-b>
</div>
</template><script>
import ComponentB from "./ComponentB";export default {
name: 'Parent',
components: {ComponentB},
}
</script><style scoped>
.outer {
margin: 20px;
border: 2px solid red;
padding: 20px;
}
</style>ComponentB.vue(组件) <template>
<div class="container">
<h3>ComponentB</h3>
计数器的值:{{thisCount}}
<!--也可以这么写:-->
<!--计数器的值:{{this.$store.state.count}}-->
</div>
</template><script>
export default {
computed:{
thisCount() {
return this.$store.state.count;
}
}
}
</script><style scoped>
.container {
margin: 20px;
border: 2px solid blue;
padding: 20px;
}
</style>路由(router/index.js) import Vue from 'vue'
import Router from 'vue-router'
import Parent from "../components/Parent";Vue.use(Router)export default new Router({
routes: [
{
path: '/parent',
name: 'Parent',
component: Parent,
}
],
})测试 访问:http://localhost:8080/#/parent
总结以上为个人经验,希望能给大家一个参考,也希望大家多多支持 。 |