赞
踩
因为直接对props的数据进行解构,例如const {a} = props,会使数据丢失响应性,需要使用toRefs和toRef保持响应性。另外直接使用props.xxx 的方式,数据不会丢失响应性。
因此,props保持响应性的方法总结如下:
1、通过 props.xxx 的形式来使用其中的 props。(在script中使用的时候,后面不需要再加.value获取值)
2、通过解构 props对象的方式调用时,需要使用toRefs和toRef来保持数据具有响应性。(在script中使用的时候,需要加.value获取值,因为现在是ref类型)
示例如下:
- <template>
- <child-component :text="text"></child-component>
- </template>
- <script setup>
- import { ref } from 'vue'
- const text = ref('初始值')
- setTimeout(() => {
- text.value = '变化值'
- }, 2000)
- </script>
- <template>
- <div>{{ props.text }}</div>
- </template>
- <script setup>
- const props = defineProps({
- text: {
- type: String,
- default: ''
- }
- })
- // 获取值
- console.log('value:',props.text)
- </script>
- <template>
- <div>{{ text }}</div>
- </template>
- <script setup>
- import { toRefs, toRef } from 'vue'
- const props = defineProps({
- text: {
- type: String,
- default: ''
- }
- })
- // 将 `props` 转为一个其中全是 ref 的对象,然后解构
- const { text } = toRefs(props)
- // 获取值
- console.log('value:',text.value)
- // 或者,将 `props` 的单个属性转为一个 ref
- const { text1 } = toRef(props, 'text')
- // 获取值
- console.log('value:',text1.value)
- </script>

store 是一个用 reactive 包裹的对象,这意味着不需要在getter 之后写.value,但是,就像setup中的props一样,我们不能对其进行解构,需要结合storeToRefs使用。另外直接使用store.xxx的形式,或者使用computed的方式也不会丢失响应性。
因此,store数据保持响应性的方法总结如下:
1、通过 store.xxx 的形式直接使用。(在script中使用的时候,后面不需要再加.value获取值)
2、通过computed计算属性的方式获取store的数据,在页面中使用。(在script中使用的时候,需要加.value获取值,因为computed需要加.value)
3、从 store 中提取属性时,保持其响应式,您需要使用storeToRefs。它将为任何响应式属性创建 refs。(在script中使用的时候,需要加.value获取值,因为现在是ref类型)
示例如下:
- import { ref } from 'vue'
- import { defineStore } from 'pinia'
- export const useSystemInfoStore = defineStore('systemInfo', () => {
- const title = ref('hello world')
- return {
- title
- }
- })
- <template>
- <div>
- {{ systemInfoStore.title }}
- </div>
- </template>
- <script setup>
- import { computed } from 'vue'
- import { useSystemInfoStore } from '@/store/systemInfoStore'
- const systemInfoStore = useSystemInfoStore()
- // 获取值
- console.log('value:',systemInfoStore.title)
- </script>
- <template>
- <div>
- {{ title }}
- </div>
- </template>
- <script setup>
- import { computed } from 'vue'
- import { useSystemInfoStore } from '@/store/systemInfoStore'
- const systemInfoStore = useSystemInfoStore()
- const title = computed(() => systemInfoStore.title);
- // 获取值 computed必须加.value
- console.log('value:',title.value)
- </script>
- <template>
- <div>
- {{ title }}
- </div>
- </template>
- <script setup>
- import { storeToRefs } from 'pinia'
- import { useSystemInfoStore } from '@/store/systemInfoStore'
- const systemInfoStore = useSystemInfoStore()
- // 使用storeToRefs解构
- const { title } = storeToRefs(systemInfoStore)
- // 获取值
- console.log('value:',title.value)
- </script>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。