Vuex
解决不同组件的数据共享,与数据持久化
1.npm install vuex --save
2.新建store.js 并引入vue vuex ,Vue.use(Vuex)
3.state在vuex中用于存储数据
var state = {
count:1
}
4.mutations里放的是方法,主要用于改变state中的数据
var mutations = {
incCount(){
++state.count;
}
}
5.实例化vuex.Store
consta store = new Vuex.Store({
state,
mutations
})
6.export default store;
7.组件A中引入store
import store from ‘../store.js‘
8.注册
mounted(){},
store
9.
通过this.$store.state.count引用属性
通过this.$store.commit.(‘incCount‘))引用方法
import Vue from ‘vue‘; import Vuex from ‘vuex‘; Vue.use(Vuex); var state = { count:1 } const mutations = { run(){ ++state.count; } } const store = new Vuex.Store({ state, mutations }); export default store;
<template> <div id="app"> <router-link to="/home">Home组件</router-link> <router-link to="/news">News组件</router-link> <hr> <router-view></router-view> </div> </template> <script> export default { name: ‘app‘, data () { return { msg: ‘Welcome to Your Vue.js App‘ } } } </script> <style lang="scss"> </style>
<template> <div id="news"> News组件 {{this.$store.state.count}} </div> </template> <script> import store from ‘../utils/store.js‘ export default { data() { return{} }, store }; </script>
<template> <div id="home"> Home组件 {{this.$store.state.count}} <br> <button @click="addstate()">添加state</button> </div> </template> <script> import store from ‘../utils/store.js‘ export default { data() { return{} }, store, methods:{ addstate(){ this.$store.commit(‘run‘) } } }; </script>
原文地址:https://www.cnblogs.com/chenyishi/p/9190609.html
时间: 2024-10-10 13:19:23