这篇文章给大家分享的是有关Vue简单状态管理之store模式是什么的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
store 状态管理模式的实现思想很简单,就是定义一个 store 对象,对象里有 state 属性存储共享数据,对象里还存储操作这些共享数据的方法。在组件中将 store.state 共享数据作为 data 的一部分或全部,在对 store.state 对象里的共享数据进行改变时,必须调用 store 提供的接口进行共享数据的更改。
以下以一个简单 todo-list demo 来介绍 store 状态管理模式
//store.js
export const store = {
state: {
todos: [
{text: '写语文作业', done: false},
{text: '做数学卷子', done: false}
]
},
addTodo(str){
const obj = {text: str, done: false}
this.state.todos.push(obj)
},
setDone(index){
this.state.todos[index].done = true
}
}
//A.vue
<template>
<div class="A">
我是 A组件
<ul>
<li v-for="(todo,index) in todos"
:key="index" :class="todo.done?'done':''" @click="setDone(index)">
{{todo.text}}
</li>
</ul>
</div>
</template>
<script>
import {store} from '../store/store.js'
export default {
name: 'A',
data(){
return store.state
},
methods: {
setDone(index){
store.setDone(index)
}
}
}
</script>
<style scoped>
.A{
background: red;
color: white;
padding: 20px;
}
.A li.done{
background: green;
}
</style>
//B.vue
<template>
<div class="B">
<div>
我是 B 组件,在下方输入框输入任务在 A组件 中添加任务
</div>
<input type="text" v-model="text">
<button @click="addTodo">add todo</button>
</div>
</template>
<script>
import {store} from '../store/store.js'
export default {
name: 'B',
data(){
return {
text: ''
}
},
methods:{
addTodo(){
if(this.text){
store.addTodo(this.text)
}
}
}
}
</script>
<style scoped>
.B{
background: yellow;
padding: 20px;
}
</style>
//App.vue
<template>
<div id="app">
<A />
<B />
</div>
</template>
<script>
import A from './components/A.vue'
import B from './components/B.vue'
export default {
name: 'App',
components: {
A,
B
}
}
</script>
可以看到,在 A组件 中显示的数据,在 B组件 中进行添加和修改,就是通过数据共享的方式进行数据通信,简单的 store模式 就是这样的运用方式。
Vue是一套用于构建用户界面的渐进式JavaScript框架,Vue与其它大型框架的区别是,使用Vue可以自底向上逐层应用,其核心库只关注视图层,方便与第三方库和项目整合,且使用Vue可以采用单文件组件和Vue生态系统支持的库开发复杂的单页应用。
感谢各位的阅读!关于“Vue简单状态管理之store模式是什么”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。