[Vuejs]-Using data inside component with Vuejs

0👍

This is how I would recommend rewriting your code:

  1. Define your add-domain component before you mount your Vue app to keep things more organised and easy to read.
  2. Pass down the methods and data from your component that you will need inside your <slot> content.
  3. Create a changeUrl method in your component and pass this down as well to allow your slot content to update the URL value.
const addDomain = {
  data: function () {
    return {
      url: ""
    };
  },
  methods: {
    submit: function () {
      console.log(this.url);
    },
    changeUrl(ev) {
      this.url = ev.target.value;
    },
  },
  template:
    `<div>
      <slot :url='url' :submit='submit' :changeUrl='changeUrl'>
      </slot>
    </div>`
};

var Modal = new Vue({
  el: "#modal",
  data: {
    component: false
  },
  components: {
    addDomain
  }
});

// HTML:
<add-domain v-if="component === 'add-domain'" v-slot="{ url, changeUrl, submit }">
  ...
  <input
    type="text"
    class="form-control"
    :value="url"
    @input="changeUrl"
  />
  ...
</add-domain>

Leave a comment