本文介绍了如何在 vue 组件中更新 props的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Vue 中创建自己的复选框.我想使用 fontawesome 中的两个图标(锁定和解锁).当我的复选框被选中时,图标应该被锁定否则解锁.

这是我的代码:

<div><i @click="statusChanged()";v-if="!checked";class=fas fa-lock-open lock"></i><i @click="statusChanged()";v-if=已检查"class=fas fa-lock lock"></i>

</模板><script lang="ts">从'vue'导入Vue;从 'vue/types/options' 导入 { Prop };导出默认 Vue.extend({道具: {检查:{类型:布尔值作为 Prop,},},方法: {状态改变(){this.checked = !this.checked;},},});

我收到一个错误:

无法分配给 'checked',因为它是一个常量或只读属性

你能帮助解决这个问题吗?

解决方案

看看 prop.sync 修饰符.它正是为这种情况而设计的,您希望更新父值但将其作为属性传递给子级:
https://vuejs.org/v2/guide/components-custom-events.html#sync-Modifier

基本上,您将道具标记为sync'able:

为了更新父级,您从子级发出 update:prop 事件:
this.$emit('update:checked', !this.checked)

这应该可以帮助您开始解决方案:
https://codesandbox.io/s/97rl86n64

I want to create my own checkbox in Vue. I want to use two icons from fontawesome (lock and unlock). When my checkbox is checked then icon should be locked otherwise unlocked.

Here is my code:

<template>
   <div>
      <i @click="statusChanged()" v-if="!checked" class="fas fa-lock-open lock"></i>
      <i @click="statusChanged()" v-if="checked" class="fas fa-lock lock"></i>
   </div>
</template>
<script lang="ts">
import Vue from 'vue';
import { Prop } from 'vue/types/options';
export default Vue.extend({
    props: {
        checked: {
        type: Boolean as Prop<boolean>,
    },
},
methods: {
    statusChanged() {
        this.checked = !this.checked;
    },
},
});

I received an error:

Can you help resolve this issue?

解决方案

Take a look at the prop.sync modifier. It is made for exactly this kind of case where you want to update the parents value but pass it as a property to the child:
https://vuejs.org/v2/guide/components-custom-events.html#sync-Modifier

Basically you mark the prop as being sync'able:
<Checkbox :checked.sync="foo"></Checkbox>

And to update the parent you emit an update:prop event from the child:
this.$emit('update:checked', !this.checked)

This should get you started for your solution:
https://codesandbox.io/s/97rl86n64

这篇关于如何在 vue 组件中更新 props的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 17:19