一般当父组件需要给子组件传值的时候会用到。
vue2在父组件里引入子组件以后需要在components里面注册后再使用;
- 父组件
-
- import SonCompnents from "./cpmponents/SonCompnents.vue"
- components: {
- SonCompnents,
- },
- data(){
- return {
- info:'个人信息'
- }
- }
- 子组件
- props:['info'] //数组写法
- props:{
- info:Stirng //对象写法
- }
vue3的父组件引用后直接使用即可;
- 父组件
-
- import SonCompnents from "./cpmponents/SonCompnents.vue"
- import {ref }from 'vue'
- let info = ref('props传参')
- 子组件
- import {ref,computed} from 'vue'
- const props = defineProps({
- info:String
- })
- 一般props的值就用computed来接收使用
- let getInfo = computed(()=>{
- return props.info
- })
用于子组件向父组件传递信息,修改父组件传的props的值
- 子组件
-
- data(){
- return{
- name:'子组件'
- }
- }
-
- methods:{
- sendMes(name){
- this.$emit('getMes',name) 触发父组件绑定的getMes事件从而触发对应的方法,后面是传的参数
-
- }
- }
- 父组件
-
"changeMes"> -
- import SonComponet from '@/components/SonComponet'
-
- data(){
- return(){
- name:'原本的值'
- }
- }
-
- methods:{
- changeMes(name){
- this.name=name
- }
-
- }
- 子组件
"sendMes">子组件给父组件传值 -
- const emits = defineEmits(["close"]);
- const sendMes = ()=>{
- emits("close","传的参数") //可传可不传
- }
- 父组件
-
"changeMes"> -
- import SonComponent from '@/components/SonComponent.vue'
- import {ref} from 'vue'
-
- let mes = ref('原值')
- const changeMes = (name)=>{
- mes.value = name
-
- }
用于对数据的监听并实时做出处理;
- 子组件
- 1.监听对象的一个属性值并实时修改另一个值
- watch: {
- 'form.currency': {
- handler(newValue, oldValue) {
- if (newValue == 'USD') {
- this.currencyType = '万美元';
- } else {
- this.currencyType = '万元';
- }
- },
- deep: true,
-
- },
- 'form2.currency': {
- handler(newValue, oldValue) {
- if (newValue == 'USD') {
- this.currencyType = '万美元';
- } else {
- this.currencyType = '万元';
- }
- },
- deep: true
- }
- },
这里的场景是子组件是弹窗,父组件是表格,在表格中引入,点击编辑,子组件弹出框的数据随之更改;


- 子组件
- import {ref,watch} from 'vue'
-
- const props = defineProps({
- info:Obeject
- })
- let info = ref({})
-
- 当监听的值是一个对象的某个属性值时,watch的第一个参数就需要写成函数,其他直接写参数即可
- watch(
- ()=>props.info //如果只是子组件本身的一个值 name,
- (newValue,oldValue)=>{
- if(newValue){
- form = {
- name = newValue.name
- price= newValue.price
-
- }
- }
- },
- { 第三个对象配置watch的属性
- deep:true
-
- }
- )
watchEffect的作用是不需要指定需要监听的属性,而是监听一个回调,当回调内所使用的数据发生变化时,回调就会执行;
缺点:1.不会立刻执行(可用immediate)解决;2.获取不到newValue和oldValue;
更多知识点得参考其他教程
- import {watchEffect,ref} from 'vue'
- let a = ref(1)
- let b = ref(1)
-
- const stop =watchEffect(()=>{
-
- console.log(a,b) 一但a或b的值发生了改变,这个打印函数就会执行
-
- })