Vue 3.0 全家桶抢先体验(3)

<template> <div> <h1>test count: {{count}}</h1> <div>count * 2 = {{doubleCount}}</div> <div>state from vuex {{a}}</div> <button @click="add">add</button> </div> </template> <script> import { ref, computed, watch, getCurrentInstance } from 'vue' export default { setup () { const count = ref(0) const add = () => { count.value++ } watch(() => count.value, val => { console.log(`count is ${val}`) }) const doubleCount = computed(() => count.value * 2) const { ctx } = getCurrentInstance() console.log(ctx.$router.currentRoute.value) const a = computed(() => ctx.$store.state.test.a) return { count, doubleCount, add, a } } } </script>

这里我们通过计算属性来引用 Vuex 中的状态:

const a = computed(() => ctx.$store.state.test.a)

ctx 是上节中我们提到的当前组件实例

更新 Vuex 状

更新 Vuex 状态仍然使用 commit 方法,这点和 Vuex 3.0 版本一致:

<template> <div> <h1>test count: {{count}}</h1> <div>count * 2 = {{doubleCount}}</div> <div>state from vuex {{a}}</div> <button @click="add">add</button> <button @click="update">update a</button> </div> </template> <script> import { ref, computed, watch, getCurrentInstance } from 'vue' export default { setup () { const count = ref(0) const add = () => { count.value++ } watch(() => count.value, val => { console.log(`count is ${val}`) }) const doubleCount = computed(() => count.value * 2) const { ctx } = getCurrentInstance() console.log(ctx.$router.currentRoute.value) const a = computed(() => ctx.$store.state.test.a) const update = () => { ctx.$store.commit('setTestA', count) } return { count, doubleCount, add, a, update } } } </script>

这里我们点击 update a 按钮后,会触发 update 方法,此时会通过 ctx.$store.commit 调用 setTestA 方法,将 count 的值覆盖 state.test.a 的值

总结

通过我第一时间体验 Vue 3.0-beta 版本后,感觉 Vue 3.0 已经具备了商业项目开发的必备条件,语法精炼,不管是代码可读性还是运行效率都非常赞。但由于未深入使用,目前还无法提出更多问题,需要在项目实战中进一步发现和总结问题,再和大家分享交流。

到此这篇关于Vue 3.0 全家桶抢先体验的文章就介绍到这了,更多相关Vue 3.0 全家桶内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/7b610787d9037598ee802a4f85a8c7d7.html