Vue.observable
使对象反应。在内部,Vue在data
函数返回的对象上使用它。
返回的对象可以直接在渲染函数和计算属性中使用,并在变异时触发适当的更新。它还可以用作简单场景的最小跨组件状态存储:
store.js
import vue from 'vue';
export const store = vue.observable({count: 0});
export const mutation = {
setCount( count ){
store.count = count;
}
}
应用组件:
<template>
<div class="hello">
<p @click="setCount(testCount + 1)">+</p>
<p @click="setCount(testCount - 1)">-</p>
<test />
<p>{{testCount}}</p>
</div>
</template>
<script>
import test from './test'
import { store, mutation} from '@/store'
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
components: {
test
},
methods: {
setCount: mutation.setCount
},
computed: {
testCount(){
return store.count
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
test组件
<template>
<div>test{{testCount}}</div>
</template>
<script>
import { store } from '@/store';
export default {
computed: {
testCount(){
return store.count
}
}
}
</script>
<style scoped>
</style>
网友评论