vue中使用vuex
首先新建一个vue的项目,个人觉得这样结构比较清晰,放在现有的vue项目中也可以的,但是不要搞混乱了哈!这个案例是父子组件调用vuex中的数据,相互影响,相互独立。
项目结构如下,在components下新建Parent.vue和Child.vue,新建store文件夹,放index.js文件
1.Parent.vue
<template>
<div class="parent">
<h3>这是父组件</h3>
<div>父组件原本的内容:{{ msg }}</div>
<button @click="onChangeParentText">爸爸自己</button>
<button @click="onChangeChildText">爸爸打了儿子</button>
<child></child>
</div>
</template>
<script>
import Child from "./Child.vue";
export default {
components: {
child: Child
},
data() {
return {};
},
computed: {
msg() {
return this.$store.state.parentText;
}
},
methods: {
onChangeParentText() {
this.$store.commit("changeParentText", "爸爸自己");
},
onChangeChildText() {
this.$store.commit("changeChildText", "爸爸打了儿子");
}
}
};
</script>
<style scoped>
.parent {
background-color: #64e4d3;
height: 400px;
margin-top: 20px;
}
.parent h3{
padding-top: 20px;
}
</style>
2.Child.vue
<template>
<div class="child">
<h3>这是子组件</h3>
<div>子组件原本的内容:{{ msg }}</div>
<button @click="onChangeParentText">儿子打了爸爸</button>
<button @click="onChangeChildText">儿子自己</button>
</div>
</template>
<script>
export default {
name: "Child",
data() {
return {};
},
computed: {
msg() {
return this.$store.state.childText;
}
},
methods: {
onChangeParentText() {
this.$store.commit("changeParentText", "儿子打爸爸");
},
onChangeChildText() {
this.$store.commit("changeChildText", "儿子自己");
}
}
};
</script>
<style scoped>
.child {
background-color: #a957ec;
border: 1px solid black;
height: 200px;
margin: 10px;
}
.child h3{
padding-top: 15px;
}
</style>
3.store-----index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
childText: '我是儿子',
parentText: '我是爸爸'
}
const mutations = {
changeParentText(state, str) {
state.parentText = str;
},
changeChildText(state, str) {
state.childText = str;
}
}
const store = new Vuex.Store({
state: state,
mutations: mutations
})
export default store
4.然后在app.vue中
<template>
<div id="app">
<Parent msg='李易峰'></Parent>
</div>
</template>
<script>
import Parent from "./components/Parent.vue";
export default {
name: "App",
components: {
Parent
}
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
5.在main.js中注册store
import store from './store/index.js'
new Vue({
el: '#app',
router,
store,
components: {
App
},
template: '<App/>'
})
这样就完成vuex测试了!