Vue2使用Composition API实现替代Vuex的状态存储相关问题
问题解答
1. 双向绑定失效修复
你当前双向绑定不生效的核心原因是:setup中直接返回了reactive类型的store对象,模板无法直接访问其内部的input1属性。可以通过以下两种方式修复,推荐第二种写法:
方案1:模板加前缀
修改模板的绑定属性,同时调整setup返回值:
<template> <input v-model="store.input1" type="text"> </template> <script> import useStore from './store' export default { setup() { const store = useStore() return { store } } } </script>
方案2:用toRefs转响应式结构(推荐)
转换后模板可以直接使用input1变量,无需加前缀:
<template> <input v-model="input1" type="text"> </template> <script> import { toRefs } from 'vue' import useStore from './store' export default { setup() { const store = useStore() return { ...toRefs(store) } } } </script>
2. 全局状态重置功能实现
需要先在store中预存初始默认值,同时导出重置方法,修改后的store.ts代码如下:
// store.ts import { reactive } from 'vue' // 预存所有变量的默认值 const DEFAULT_STATE = { input1: '', // 其余变量的默认值在此补充 } const state = reactive({ ...DEFAULT_STATE }) export default () => { // 重置方法:把state的所有属性覆盖为默认值 const resetState = () => Object.assign(state, DEFAULT_STATE) return { state, resetState } }
页面中调用重置方法的代码:
<template> <input v-model="input1" type="text"> <button @click="resetState">重置所有内容</button> </template> <script> import { toRefs } from 'vue' import useStore from './store' export default { setup() { const { state, resetState } = useStore() return { ...toRefs(state), resetState } } } </script>
3. computed计算属性报错修复
你当前的computed写法有两个问题:一是用了选项式API的写法,没有正确获取到input1变量;二是computed应该直接返回计算结果,不需要给this.variable赋值。
推荐直接在setup中用组合式API的computed实现,代码如下:
<template> <input v-model="input1" type="text"> <p>当前输入长度:{{ calculateStringLength }}</p> </template> <script> import { toRefs, computed } from 'vue' import useStore from './store' export default { setup() { const { state, resetState } = useStore() // 定义响应式计算属性 const calculateStringLength = computed(() => state.input1.length) return { ...toRefs(state), resetState, calculateStringLength } } } </script>
如果要使用选项式API的computed写法,在解决第一个双向绑定问题后,修改computed的返回逻辑即可:
computed: { calculateStringLength() { return this.input1.length } }
内容的提问来源于stack exchange,提问作者kohrhea
相关产品推荐
相关产品推荐

