programing

동적으로 삽입된 문자열의 Vue 이벤트 핸들러가 작동하지 않음

minecode 2022. 10. 11. 21:23
반응형

동적으로 삽입된 문자열의 Vue 이벤트 핸들러가 작동하지 않음

코드는 다음과 같습니다.

<template>
    <div>      
      <div v-html="data"></div> <button v-on:click="replace">Click Me to replace div contents</button>
    </div>
</template>
<script>
export default {
  data() {
    return {
      data: "I will be replaced once you click on button"
    }
  },
  methods: {
    clickMe() {
      alert("worked");
    },
    replace(){
      this.data = "Why does click me not work? It is loaded from server via ajax <a href v-on:click.prevent='clickMe'>Click Me</a>";
    }
  }
};
</script>

여기를 클릭하면Click Me to replace div contents콘텐츠는 교체되지만 이벤트 핸들러의 clickMe는 실행되지 않습니다.이 데이터는 서버에서 가져오며 Vue가 이벤트 등을 처리할 수 있도록 이 문자열을 컴파일하여 Vue의 컨텍스트 내에서 사용해야 합니다.

서버 워크에서 동적 문자열을 다운로드하려면 어떻게 해야 합니까?Vue 2를 쓰고 있어요.

v-html은 컴파일되어 있지 않기 때문에 문제를 해결하려면 다음과 같은 미니 컴포넌트를 작성해야 합니다.

new Vue({
  el: '#app',
  data () {
    return {
      data: ``
    }
  },
  
  computed: {
    compiledData () {
      return {
      	template: `<p>${this.data}</p>`
      }
    }
  },
  
  methods: {
    replace () {
       this.data = `Now click on me <a href='#' @click.prevent='alert("yo")'> here </a>`
    }
  }
})
<script src="https://unpkg.com/vue@2.5.3/dist/vue.min.js"></script>


<div id="app">
  <component :is="compiledData" ></component>
  <button v-on:click="replace">Click Me to replace div contents</button>
</div>

위의 코드는 문자열 내용을 컴파일하므로 의도한 대로 함수를 실행/실행할 수 있습니다.

Vue 컴포넌트(코드펜)를 사용하는 기타 솔루션:

<script src="https://unpkg.com/vue"></script>
<div id="app">      
  <div id="someId"></div> <button v-on:click="replace">Click Me to replace div contents</button>
  <component :is="currentView"></component>
</div>

<script>
let app = new Vue({
  el: '#app',
  data: {
    currentView: null   
  },
  methods:{
    replace: function(){
      var templateFromServer = getTemplate();
       var comp=Vue.component('template-from-server', {
          template: templateFromServer,
          methods:{
            clickMe:function (){
              console.log("click");
            }            
          }
        });   
      this.currentView = comp;
    }   
  }
});

function getTemplate(){
  return "<a href v-on:click.prevent='clickMe'>Click Me</a>"
}
</script>

v-html는 Vue 템플릿으로 컴파일되지 않습니다.문서에서:

내용은 플레인 HTML로 삽입되며 Vue 템플릿으로 컴파일되지 않습니다.v-html을 사용하여 템플릿을 구성하려는 경우 대신 구성 요소를 사용하여 솔루션을 다시 생각해 보십시오.

참조: https://vuejs.org/v2/api/ #v-timeout

HTML 문자열에서 VueJS 코드를 렌더링할 수 없습니다.

v-if를 사용하여 이 문제를 해결할 수 있습니다.

<div>
<div v-if="data">I will be replaced once you click on button</div> 
<div v-else>Why does click me not work? It is loaded from server via ajax <a href @click.prevent='clickMe'>Click Me</a></div>
<button @click="replace">Click Me to replace div contents</button>
</div>

<script>
export default {
  data() {
    return {
      data: true
    }
  },
  methods: {
    clickMe() {
      alert("worked");
    },
    replace(){
      this.data = !this.data;
    }
  }
};

문자열에서 일반 javascript 함수를 호출할 수 있지만 vuejs 함수는 호출할 수 없으므로 onclick 이벤트도 작동합니다.

언급URL : https://stackoverflow.com/questions/47202998/vue-event-handler-on-dynamically-inserted-string-does-not-work

반응형