Home > Software engineering >  vuejs bind url from data to click method
vuejs bind url from data to click method

Time:11-28

I have a set of data that has urls nested in the data model. I want to bind the url from from the data to click event. Right now it does not get the exact url just the variable. It should open the url in the data in a blank tab.

new Vue({
  el: "#app",
  data: {
    chocs: [
      { url: "https://yahoo.com"},
   
    ]
  },
  methods: {
    myclick2: function(choc){
    alert("test")
    window.open(choc.url)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
 
  <h2>
  my hat
  </h2>
  <button v-on:click="myclick2(choc)">
  my link
  </button>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You have defined the data as an array named chocs. Containing an object with an url.

This would be saved as follows:

cohc: [
  { url: "https://yahoo.com/" }
]

This array could contain more items, but right now it only contains this one item. If you want to "open" that item you would do something like the following:

cohcs: [
  { url: "https://yahoo.com/" }
]

console.log(cohcs[0]) // returns: { url: "https://yahoo.com/" }

The 0 is the index of the array.

In case of the code provided above, you can define your v-on:click event like this:

<button v-on:click="myclick2(chocs[0])">

If you only want to save one link. you could also define your data as

  data: {
    chocs: { url: "https://yahoo.com"}
  },

CodePudding user response:

There are multiple little error in your code

First the correct code:

new Vue({
  el: "#app",
  data() {
    return {
      chocs: [
        { url: "https://yahoo.com"},
      ]
    }
  },
  methods: {
    myclick2: function(){
      alert("test ",this.chocs[0].url)
      window.open(this.chocs[0].url, "_blank")
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
 
  <h2>
  my hat
  </h2>
  <button v-on:click="myclick2()">
  my link
  </button>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

List of errors:

  • the data part is written as data(){return{...}}
  • in your function you were calling choc instead of chocs (you have access to the data, don't pass something that is undefined as parameter)
  • because you use data, you need to call it with this
  • based on the structure from chocs, you have an object in an array (the first place in the array; index 0)
  • if you want to open a new window, you can add "_blank"
  • Related