provide 传递响应式值时子组件对应页面并未发生改变
来源:3-21 Provide - Inject
慕莱坞3345942
2022-06-25
老师你好,学习 3-21 Provide - Inject 时的问题
点击按钮后 language.value
确实变为了 en / cn ,但是页面显示并未变化
能帮忙看下为什么吗
以下是我的代码:
子组件:SonInject.vue
<template>
<h2>{{lang}}</h2>
<h2>{{language}}</h2>
</template>
<script lang="ts">
import { defineComponent, inject } from 'vue';
export default defineComponent({
name: 'SonInject',
setup() {
const lang = inject('lang');
const language = inject('language');
return {
lang,
language
}
}
})
</script>
<style scoped>
</style>
App.vue
<template>
<!-- <HelloWorld msg="Welcome to Your Vue.js + TypeScript App"/> -->
<h2>X:{{x}} Y:{{y}}</h2>
<SonInject></SonInject>
<button @click="changeLanguage('en')">英文</button>、
<button @click="changeLanguage('ch')">中文</button>
<hr>
<Suspense>
<template #default>
<!-- Suspense 只支持单个根节点 -->
<div>
<dog-show></dog-show>
<async-show></async-show>
</div>
</template>
<template #fallback>
<h1>ASYNC SHOW LOADING</h1>
</template>
</Suspense>
<hr>
<h1 v-if="loading">Loading...</h1>
<img v-if="loaded && res" :src="res[0].url" alt="随机猫猫ipg">
</template>
<script lang="ts">
import { defineComponent, ref, watch, onErrorCaptured, provide } from 'vue';
// import useMousePoint from './hooks/useMousePoint_ref'
import useMousePoint from './hooks/useMousePoint_reac';
import useURLLoader from './hooks/useURLLoader';
import AsyncShow from './components/AsyncShow.vue';
import DogShow from './components/DogShow.vue';
import SonInject from './components/SonInject.vue'
interface DogResult {
message: string,
status: string
}
interface CatResult {
id: string,
url: string,
width: number,
height: number
}
export default defineComponent({
name: 'App',
components: {
AsyncShow,
DogShow,
SonInject
},
setup(){
// provide 全局提供数据
// 参数一:数据名称 参数二:数据值
provide('lang', '《 Chinese 》');
const language = ref('English');
const changeLanguage = (type: string) => {
language.value = type;
console.log(language.value, type);
}
provide('language', language.value);
const error = ref(null);
// 错误处理钩子(每当事件处理程序或什么周期钩子抛出错误时调用)
onErrorCaptured((err: any)=>{
error.value = err;
// 错误向上传播
return true;
})
const {x, y} = useMousePoint();
// const {res, loading, loaded} = useURLLoader<DogResult>('https://dog.ceo/api/breeds/image/random');
const {res, loading, loaded} = useURLLoader<CatResult[]>('https://api.thecatapi.com/v1/images/search?limit=1');
// Dog
/* watch(res, () => {
if(res.value){
console.log('value', res.value.message);
}
}) */
// Cat
watch(res, () => {
if(res.value){
console.log('value', res.value[0].url);
}
})
return {
x,
y,
res,
loading,
loaded,
changeLanguage
}
}
});
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
写回答
1回答
-
同学你好 在于你 provide 没有直接提供一个响应式对象,而是将响应式对象的值传了进入,
provide('language', language.value) 替换成 provide('language', language)
012022-06-26
相似问题
createApp 修改props
回答 1
props传值后失去响应性
回答 1