0
votes

I'm taking an online course which corrects code using a bot. In this course I'm learnig HTML, JS and Vue.JS.

The assignemnt is to create a component, greet that produces <div>Welcome, Alice!</div> when it's called using <greet></greet> The assignment also wants me to use data and methods to make it so it says Welcome, Bob instead when you click om the div element in the component. It tells me to use the data and methods key in the component.

This is my code so far, but I'm stuck. HTML

<body>
    <div id="app"><greet></greet>
    </div>
</body>

Vue code:

Vue.component('greet', {
  data() {
    return {   
    }
  },
  template: '<div>Welcome</div>'
})

new Vue({ el: '#app' })

How do I make it so it says Welcome, Alice! and when pressed, it says Welcome, Bob! ? The bot gives me an output of

file.js
    ✓ exists
    ✓ is valid JavaScript
    1) renders the correct markup when no clicks are made
    2) renders the correct markup when one click is made
2

2 Answers

0
votes

In your data property, define a variable that will hold access to the name so to speak. In this case, we'll initialize it with a value of Alice:

data () {
  return {
    name: 'Alice'
  }
}

We can add a click method now and bind it to our div element so that it will swap the name:

methods: {
  swap () {
    this.name = 'Bob'
  }

}

Finally, we need to modify our template to receive a click handler and use dynamic bindings to display our name property from our data object:

template: `<div @click="swap">Welcome, <span v-text="name"></span></div>`

Note that in the above illustration the v-text is a directive and we have bound the value of our name property to it, which we modify through the @click handler we assigned to the swap function.

0
votes

You can use the event @click on the div, with that you bind the click event to a specific method in this case I create toggleName()

  Vue.component('greet', {
      data() {
        return {
         name: 'Alice'
        }
      },
      methods: {
        toggleName() {
          this.name = this.name == 'Alice' ? 'Bob' : 'Alice';
        }
      },
      template: '<div @click="toggleName">Welcome {{ name }}</div>'
    })

Then we create a method that accesses to the property defined in data in this case is name When we use the reserved word this we access to our instance and from there w can access the property name. Then we create a toggle for the name.

In order to access the variable in our template we need to use the special curly braces {{ name }} this time the this is not needed.