1. 组件传值
1.1 进入页面即刻传值
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 };
}
};
import { inject } from 'vue';
export default {
setup() {
const p = inject('name');
return { p };
}
};
1.2 点击传值
<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>
<template>
<div class="new">
这是子组件
<!-- <h1>姓名:{{ p }}</h1> -->
</div>
</template>
<script>
export default {
setup() {
function receive(val) {
console.log(val);
}
return { receive };
}
};
</script>
<style scoped lang="scss">
.new {
background-color: blue;
height: auto;
}
</style>
2. 封装
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'">button3</button>
</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">button</button>
</div>
</template>
<script>
import { computed } from 'vue';
import { useStore } from 'vuex';
export default {
setup() {
const store = useStore();
const res = computed(() => {
console.log(store.state.name);
return store.state.name;
});
const func = () => {
store.dispatch('sub', '张朝阳');
};
return { res, func };
}
};
</script>
<style scoped lang="scss">
.new {
background-color: blue;
height: auto;
}
</style>
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);
}
}
});
import store from './store';
createApp(App)
.use(store)
|