使用vue.js增加和呈现文本

时间:2018-12-24 09:11:59

标签: vue.js vuejs2

我正在尝试做一些非常简单的事情。递增数字:

<div>
   <button v-on:click="increase">Add 1</button>
   <p>{{ sayHello() }} and {{ counter }}</p>
</div>

这将在此处更改事件:

<b-form-input v-bind="renderText(counter)"
    type="text"
    placeholder="Type Alex"></b-form-input>

这应该只显示文本框中的内容。

<b-form-input v-bind="foo"
   type="text"
   placeholder="Enter your name"></b-form-input>

 <p>Value: {{ foo }} and {{counter}}</p>

完整代码:但这是唯一可以在sayHello()方法中使用的代码。

<template>
    <div>
        <form>
            <div>
                <button v-on:click="increase">Add 1</button>
                <p>{{ sayHello() }} and {{ counter }}</p>
            </div>
            <div>
                <b-form-input v-bind="foo"
                              type="text"
                              placeholder="Enter your name"></b-form-input>

        <b-form-input v-bind="renderText(counter)"
                   type="text" placeholder="Type Alex"></b-form-input> 
               <p>Value: {{ foo }} and {{counter}}</p>
              </div>
          </form>
      </div>
</template>

<script lang="ts">

    import Vue from 'vue';


    export default Vue.extend({

        name: 'Hobbies',

        methods: {

            data:{
              foo: '',
              counter: 0
            },

            sayHello: function () {
                return 'Alex'
            },

            increase: function () {
                this.counter++;
            },
            renderText: function (event) {
                if (event == 5){
                    return 10
                } else{
                    return 16
                }
            }
        }

    });

</script>

<style scoped>

</style>

data放在方法之外时,我得到:

enter image description here

1 个答案:

答案 0 :(得分:2)

您将data放在methods内,它应该位于根目录级别,因为我们位于组件it must also come as a function中:

export default {
  name: 'Hobbies',
  data: function(){
    return { foo: '', counter: 0 };
  },
  methods: {
    sayHello: function () { return 'Alex' },
    increase: function () { this.counter++; },
    renderText: function (event) {
      if (event == 5){
        return 10
      } else{
        return 16
      }
    }
  }
}