如何在Vue2中通过HTML运行组件的方法

时间:2018-07-12 13:21:12

标签: javascript html methods vue.js components

我有一个.vue文件ServiceList,该文件导入了组件{​​{1}}。我想像这样在Information.vue的模板中循环运行Information的代码:

ServiceList

ServiceList.vue <template> <div> <h1>Headline</h1> <div v-for="service in services"> <h2>{{ service.name }}</h2> <information v-bind:service="service"/> </div> </div> </template> <script> import Information from './Information' ... (more components here) export default { components: { Information, ... (more components here) }, ... (rest of export here) } </script> 如下所示:

Information

我试图做类似的事情

Information.vue

<template>
  <div>
    <p v-bind:id="'info'+service.id"/>      
  </div>  
</template>

<script>

export default {
  props:['service'],
  data: function () {
    return {
        services: this.$store.state.Services.data
    }
  },
  methods: {
    getInfo: function (service) {
        var info = '<b>Servicename:</b> <br>';
        info += service.name;

        ... (method adds more to 'info' here)

        document.getElementById('info'+service.id).innerHTML = info;
    }
  }
}

</script>

但它似乎永远无法工作。奇怪的是,当我将其设置为按钮时,

<template>
  <div>
    <p v-bind:id="'info'+service.id"/>  
    {{ getInfo(service) }}  
  </div>  
</template>

它完美地工作!但是我不需要按钮,只希望它出现。

1 个答案:

答案 0 :(得分:0)

对于这种琐碎的情况,您不需要在Vue js中操作DOM,只需添加要模板化的所有内容并删除getInfo方法即可,例如:

Information.vue

<template>
   <div>
     <p>
       <b>Servicename:</b> <br>
       {{ service.name }}<br>
       <b>Another Field:</b> <br>
       {{ service.anotherField }}<br>
       <b>Another Field 2 :</b> <br>
       {{ service.anotherField2 }}<br>
     </p>      
   </div>  
</template>

,如果您真的要使用html,请执行以下操作:

Information.vue

<template>
   <div>
     <p v-html="getInfo(service)"/>      
   </div>  
</template>

<script>

 export default {
    props:['service'],
    data: function () {
       return {
         services: this.$store.state.Services.data
       }
    },
    methods: {
      getInfo: function (service) {
          if (!service) return '';
          var info = '<b>Servicename:</b> <br>';
          info += service.name;

          ... (method adds more to 'info' here)

          return info;
     }
   }
 }