
// 父组件 Home.vue
import vue09 from '@/components/vue09.vue';
import { provide, reactive } from 'vue';
export default {
name: 'Home',
components: {
vue09
},
setup() {
const p = reactive({ name: 'zhangsan', age: 50, company: 'Dmall' });
provide('name', p); //传
return { p };
}
};
// 子组件 vue09.vue
import { inject } from 'vue';
export default {
setup() {
const p = inject('name'); // 收
return { p };
}
};
1.2 点击传值
// Home.vue
<template>
<div class="home">
这是父组件
<h2>{{ p.name }}</h2>
<h2>{{ p.age }}</h2>
<button @click="func">点击传值给子组件</button>
</div>
<vue09 ref="val" />
</template>
<script>
import vue09 from '@/components/vue09.vue';
import { reactive, ref } from 'vue';
export default {
name: 'Home',
components: {
vue09
},
setup() {
const val = ref();
const p = reactive({ name: 'zhangsan', age: 50, company: 'Dmall' });
const func = () => {
val.value.receive(p);
};
return { p, func, val };
}
};
</script>
<style scoped>
.home {
background-color: red;
height: auto;
}
</style>
//vue09.vue
<template>
<div class="new">
这是子组件
<!-- <h1>姓名:{{ p }}</h1> -->
</div>
</template>
<script>
// import reactive from 'vue';
export default {
setup() {
// 被父组件调用
function receive(val) {
console.log(val);
}
return { receive };
}
};
</script>
<style scoped lang="scss">
.new {
background-color: blue;
height: auto;
}
</style>
2. 封装
// src/config/public.js
// 公用的数据或者方法池
import { reactive } from 'vue';
const plblic = () => {
const info = reactive({
name: 'zhangsan',
age: 18
});
return { info };
};
export default plblic;
<template>
<div class="new">
<h1>子组件h1>
<h1>姓名:{{ p1.name }}h1>
<h1>年龄:{{ p1.age }}h1>
<button @click="p1.name = 'lisi'">button3button>
div>
template>
<script>
import plblic from '../config/public';
export default {
setup() {
const p1 = plblic().info;
return { p1 };
}
};
script>
3. vuex
组件传值异步调用不能直接修改数据,需要使用同步函数可以直接使用同步修改数据
<template>
<div class="new">
这是子组件
<h1>姓名:{{ res }}h1>
<button @click="func">buttonbutton>
div>
template>
<script>
import { computed } from 'vue';
import { useStore } from 'vuex';
export default {
setup() {
// 从vuex数据仓库里取数据
const store = useStore();
const res = computed(() => {
console.log(store.state.name);
return store.state.name;
});
// 点击调用vuex并且改变仓库里的数据
const func = () => {
// 异步调用:dispatch
store.dispatch('sub', '张朝阳');
// 同步调用:commit
// store.commit('trigger', '刘强东');
};
return { res, func };
}
};
script>
<style scoped lang="scss">
.new {
background-color: blue;
height: auto;
}
style>
// store/index.js
import { createStore } from 'vuex';
export default createStore({
// 创建数据仓库
state: { name: 'zhangsan', age: 50, company: 'Dmall' },
// 同步调用
mutations: {
trigger(state, val) {
state.name = val;
}
},
// 异步调用
// 异步调用不能直接修改数据
actions: {
sub(store, val) {
store.commit('trigger', val);
}
}
// modules: {}
});
// main.js
import store from './store';
createApp(App)
.use(store)
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)