【问题标题】:vue change div from componentvue 从组件更改 div
【发布时间】:2022-01-12 19:21:36
【问题描述】:

html

    <div class='wrapper'>
      <div class='custom'>
        <div class='item'> 1</div>
        <div class='item'> 2 </div>
        <div class='item'> 3 </div>
      </div>
      <component-vue />
    </div>

Vue

    methods: {
      doSomething() {
       document.querySelector('.custom).innerHTML = /new items
     }
    }

我的问题是,这是更改外部 div 的唯一方法吗?我需要更改items,新的来自api。也许还有另一种方式?如果只是通过innerHTML,那我该如何实现呢?

【问题讨论】:

  • 您可以使用迭代器 v-foritems 数据。

标签: vue.js vuejs2 vue-component


【解决方案1】:

例如,

<div class="item" v-for="(item, index) in items" :key="index"></div>
data() {
   return {
      items: []
   }
},
methods: {
    doSomething() {
       // Fetch data from api and load
       this.items = res.data
   }
}

编辑

<div class='custom' v-html="dataHtml"></div>
data() {
   return {
      dataHtml: `
      <div>Initial html</div>
      `
   }
},
methods: {
    doSomething() {
       // Fetch data from api and load
       this.dataHtml = createHtml(res.data) // Fictional method to parse data and transform to html f.e.
   }
}

【讨论】:

  • 显然,我没有很好地解释我需要什么。对不起。 :c html 是用ruby ​​on rails 编写的,我想从组件中影响custom 类。我们为 SEO 保留布局,然后,如果我单击过滤器中的按钮,我们将重新绘制 html
  • 然后试试v-html。我会补充回答。
  • 我是否理解正确,你需要在一般的vue中写这个,它不会工作在compoent-vue
  • 如果 vue.js 只是在component vue 中,我的回复对它不起作用,你只能使用 vainilla。但是如果 vue 应用是在父级中初始化的,那就可以了。
猜你喜欢
  • 2018-08-24
  • 2018-10-01
  • 2019-08-06
  • 2021-01-12
  • 1970-01-01
  • 2021-12-19
  • 2019-02-05
  • 1970-01-01
  • 2018-09-24
相关资源
最近更新 更多