【问题标题】:Why can't I change the text in my child component为什么我不能更改子组件中的文本
【发布时间】:2021-01-10 12:24:24
【问题描述】:

我写了一个单文件组件来展示一些东西,这里是代码

 <template>
    <el-link type="primary" @click="test()" >{{this.contentShow}}</el-link>
</template>

<script lang="ts">
import moment from 'moment'
import {Watch, Prop,Component, Vue } from 'vue-property-decorator'

export default class extends Vue{

    @Prop({ default: "111" }) private content!: string
    

    private contentShow = "11";
    
    private test(){
        alert("111");
    }

    @Watch('content')
    private contentChange(value: any) {
        this.contentShow = value;
        console.log(value);
    }
}
</script>

我想更改 el-link 的内容,但我失败了。这是代码

<userButton content="tttteeeessssttt"></userButton>

从网站控制台我可以看到没有使用“contentChange”方法。

顺便说一句,我试着这样写:

<el-link type="primary" @click="test()" >{{this.content}}</el-link>

但是说错了

vue.runtime.esm.js:619 [Vue 警告]:属性或方法“内容”未在实例上定义,但在渲染期间引用。

那么有什么问题吗?如何更改组件的内容?

非常感谢。

【问题讨论】:

  • 尝试删除内容属性的私有修饰符。
  • 我试过了还是不行

标签: javascript html typescript vue.js


【解决方案1】:

你对子组件和道具有误解吗?

您需要三个.vue 文件才能满足您的要求。

下面是一个。

<template>
  <el-link type="primary" @click="test()" >{{this.contentShow}}</el-link>
</template>

我们称之为 parent.vue。

第二个是你没有透露的。

<template>
  <userButton content="tttteeeessssttt"></userButton>
</template>

我们称之为 el-link.vue。 还是您使用的是 Element-UI?

第三个是userButton.vue。 它可能存在。


您需要在 userButton.vue 中将 content 写入 props。 在parent.vue中写是没有意义的。

在我看来,您希望在 parent.vue 中拥有原始的 content。 如果是这样,你应该在 parent.vue 中定义一个名为 content 的变量。 它不在props 中。

content必须写在el-link.vue中props

使用v-bindcontent 从 parent.vue 传播到 el-link.vue。 将:content="content" 添加到&lt;el-link&gt;

同样,将content 从 el-link.vue 传播到 userButton.vue。 将:content="content" 添加到&lt;userButton&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多