使用v-model 双向绑定父子组件

使用v-model 双向绑定父子组件

一般子组件中有input 可以在父组件使用v-model来双向绑定数据,避免父子传值,过于麻烦

步骤:

1.1子组件中使用 input

	<div class="search-input">
    <el-dropdown trigger="click" @command="handleCommand">
        <el-input
            :placeholder="placeText"
            @input="handleInput"
            clearable
            :class="{ noBorder: isBorder, hasBorder: !isBorder }"
            @focus="isBorder = false"
            @blur="isBorder = true"
            @keyup.enter.native="handleEnter"
            :value="inputText"
        >
            <svg-icon
                slot="prefix"
                class="icon-search"
                icon-class="icon-search"
            ></svg-icon>
        </el-input>
        <el-dropdown-menu
            slot="dropdown"
            style="width: 300px"
        >
            <p style="font-size: 12px; margin-left: 15px; color: #aaa">
                {{ $t('recent_search') }}
            </p>
            <el-dropdown-item
                icon="el-icon-plus"
                v-for="item in historyList"
                :key="item._id"
                :command="item.keyword"
                >{{ item.keyword }}</el-dropdown-item
            >
        </el-dropdown-menu>
    </el-dropdown>
</div>

1.2 在input中绑定@input 事件 handleInput (名称自定义)

	props: { inputText: String},
	model: {
    prop: 'inputText', //v-model 绑定的数据 需要改变子组件数据可以用 :value 来绑定			     数据,不要使用v-model 在子组件中绑定数据
    event: 'change' || 'blur' || 'keyup.enter.native',  //可以使用或逻辑绑定多种input事件
},

1.3绑定事件传递给父组件

	methods: {
    getSearchHistory() {
        getHistory(this.query).then((res) => {
            this.historyList = res.data.data.payload
        })
    },
    handleInput(event) {
        this.$emit('change', event)
        if (this.query.keyword === '') {
            delete this.query.keyword
            this.getSearchHistory()
        } else {
            this.getSearchHistory()
        }
    },
    handleCommand(command){
        this.$emit('searchCommand',command)
    },
    handleEnter(event) {
        this.$emit('keyup.enter', event)
    },
},

2.1 父组件接收

	<SearchInput
        :placeText="$t('search_placeholder1')"
         :query="searchQuery"
         @change="searchChange"
         v-model="inputText"  //使用双向绑定
         @keyup.native.enter="searchUser" //传递过来的键盘事件
         @searchCommand ="searchCommand"
    ></SearchInput>

这样就可以简化父子组件双向传值的麻烦

子组件中要绑定数值一定要用 :value 不然会报错

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值