> 文章列表 > vue2.0 父组件向子组件动态传参

vue2.0 父组件向子组件动态传参

vue2.0 父组件向子组件动态传参

  • 组件向子组件动态传参

    需求

    • 父组件是文章管理列表,带有一个编辑按钮
    • 子组件(editor)是一个内嵌的富文本编辑器:点击编辑按钮,弹出Dialog框,富文本编辑器的内容显示为当前文章内容(暂且设为content属性)
    • 我们需要传递content属性到子组件(editor),但是子组件中v-model无法绑定props中的content,因此子组件中的文本内容绑定的是data中的html属性,我们需要将content传递并且赋值给html。

    当前问题

    • 按照props传参(子组件第一次可以接收content并且更新页面内容,当时当我们点击编辑其他文章,这时候content虽然有变化,但是无法更新到子组件html属性上面(相当于没有监听变化),导致页面无法更新到当前文章的content,仍然显示的是之前的content)

      父组件

      <el-form-item label="内容"><WangEditor ref="editor" :content="formLabelAlign.content" />
      </el-form-item>
      

      子组件

      <template><Editorstyle="height: 500px; overflow-y: hidden;"v-model="html":defaultConfig="editorConfig":mode="mode"@onCreated="onCreated"/>
      </template>
      <script>
      import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
      export default{name: 'WangEditor',data() {return {html: this.content,}},props:['content'],
      }
      </script>
      

    解决办法

    在子组件加上content的监听,当content变化,再给文本编辑器内容绑定的html属性赋值.

    watch:{content(newVal, oldVal){console.log('content change')console.log(newVal)this.html = this.content}
    },