v-model

Jessie Ko·2023년 8월 9일
0

vue

목록 보기
1/1
post-thumbnail

Component v-model is a two-way binding to make codes cleaner look aka syntactic sugar.

difference from v-bind?

<input v-model="something">

<input
   v-bind:value="something"
   v-on:input="something = $event.target.value"
>

emit vs v-model between parent and child components

Also, when communicating between parent and child components, child component can update value in Parent component using v-model instead of using emit.

using v-model

// use v-model from ParentComponent to call child component 
<ChildComponent v-model="dataFromParent"></ChildComponent>
// child component 
export default {
	 props: {
        value: Array, // data from Parent Component using v-model
    },
    components: {
    },
    data() {
        return {
        }
    },
    watch: {
    },
    created() {
    },
    mounted() {
    },
    computed: {
    },
    methods: {
        onChange(record) {
                this.value.push(record); // Parent Component is updated 
          		// this.value = record -> this will give a mutation warning: "Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders." 
        },
     
    }
}

using emit

// Parent Component
<ChildComponent v-bind:updated="callParentMethod(arguments[0])"></ChildComponent>
// Parent Component
import childComponent from './child-component'

export default {
    components: {
      'ChildComponent': childComponent
    },
    data() {
        return {
          value: [],
        }
    },
    watch: {
    },
    created() {
    },
    mounted() {
    },
    computed: {
    },
    methods: {
        callParentMethod(arg) {
          this.value.add(arg);
        },
     
    }
}
// child component 
export default {
	 props: {
    },
    components: {
    },
    data() {
        return {
        }
    },
    watch: {
    },
    created() {
    },
    mounted() {
    },
    computed: {
    },
    methods: {
        onChange(record) {
			this.$emilt('updated', record); //custom event updated to send data from child -> Parent         		
        },
     
    }
}
profile
only live once, live the life i love

1개의 댓글

comment-user-thumbnail
2023년 8월 9일

즐겁게 읽었습니다. 유용한 정보 감사합니다.

답글 달기