一个简简单单的案例
app.vue
<template>
<div>
app
<Second/>
</div>
</template>
<script>
import { provide } from 'vue';
import Second from './components/Second.vue'
export default {
components:{
Second
},
setup(){
//const data = 'hello world--from app';
const method = () => console.log('hello world!!!---from app');
//provide('data',data);
provide('method',method)
}
}
</script>
/components/Second.vue
<template>
<div>
second page:{{ data }}
<Third/>
</div>
</template>
<script>
import { inject } from 'vue';
import Third from './Third.vue'
export default {
name:'second',
components:{
Third
},
setup(){
const data = inject('data','second data value');
// app没有provide data,不是provide data的值,是直接没有provide data;
// 这时候会给data赋值 "second data value"
const method = inject('method');
method();
return {
data,
method
}
}
}
</script>
/components/Third.vue
<template>
<div>
<p>third page: {{ data }}</p>
</div>
</template>
<script>
import { inject } from 'vue';
export default {
name: 'third',
components: {},
setup(){
const data = inject('data','third data value');
const method = inject('method');
method();
return {
data,
method
}
}
}
</script>
<style>
</style>
标签:vue,const,provide,setup,inject,vue3,data,method
From: https://www.cnblogs.com/pansidong/p/17260767.html