skip to Main Content

The script

<script>
    import { ref, reactive } from 'vue';
    export default {
      data() {
        const todo = ref('');
        const list = reactive([]);
        return { todo, list };
      },
      components: {
        navbar,
      },
      methods: {
        render() {
          console.log(this.list.length);
          return this.list
            .map((item, index) => {
              return `<div class="task"><p>${item.todo}</p><button @click="list.splice(index, 1)">del</button></div>`;
            })
            .join('');
        },
      },
    };
    </script>

The Html

  <div class="list-container">
    <div class="task-container" v-if="list.length" v-html="render()"></div>
    <div class="task-container" v-else>nothing in here</div>
  </div>

The data structure in the list array

{todo: 'text', checked: false},
...

I’m building a todo app so I’m trying to remove the selected todo from the list array without using v-for or emit but the @click directive is being read as a string. How can I get it to work?

I’d like to know how to do it this way specifically so that’s why I don’t want to use the other methods mentioned above.

2

Answers


  1. This is not going to work.

    Contents of v-html are inserted as plain HTML – Vue template syntax will not be processed. If you find yourself trying to compose templates using v-html, try to rethink the solution by using components instead.

    https://vuejs.org/api/built-in-directives.html#v-html

    Login or Signup to reply.
  2. i don’t think this is best the way to handle or work and learn vue but for your information what can be done is create a method remove task and add a mounted lifecycle hook to assign the removeTask method to the window object. This way, it can be accessed from within the HTML string.

    <script>
     import { defineComponent, onMounted, ref, reactive } from 'vue';
     export default {
     data() {
    const todo = ref('');
    const list = reactive(['ds', 'dsd ', 'ds']);
     return { todo, list };
     },
     components: {
    //
     },
    methods: {
    removeTask(index) {
      this.list.splice(index, 1);
    },
    render() {
      console.log(this.list.length);
      const renderedTasks = this.list
        .map((item, index) => {
          return `<div class="task"><p>${item.todo}</p><button onclick="removeTask(${index})">del</button></div>`;
        })
        .join('');
    
      return renderedTasks;
    },
    },
     mounted() {
      window.removeTask = this.removeTask;
     },
    };
    

    By the way {{item.todo}} will be undefined as per as your logic do change it and everything will work as you wanted.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search