首页 文章

单击按钮上的vue组件和警报

提问于
浏览
0

我试图让我的按钮(在vue组件内)在按下时显示警告,并且消息是输入字段内容 .

到目前为止我有以下内容:

HTML

<vue-form-input placeholder="Name"></vue-form-input>     
    <vue-form-submit button-text="Submit"></vue-form-submit>

JS

Vue.component('vue-form-input', {
props: {
    placeholder: {
        String,
        required: true
    }
},
template:`
    <div>
        <input type="text" class="form-control" :placeholder="placeholder">
    </div>` });   

Vue.component('vue-form-submit', {
props: {
    buttonText: {
        String,
        required: true,
        default: 'Submit' }

},
template:`
    <div>
        <button v-on:click="submitBut" class="btn btn-lg btn-primary btn-block" type="submit">{{buttonText}}</button>
    </div>` });


new Vue({
        el: '#forms',
        data: {

        },
        methods: {
            submitBut: () => {
                alert('Blablabla')
            }
        }, })

存在控制台错误1)属性或方法“submitBut”未在实例上定义,但在呈现期间引用 . 确保在数据选项中声明反应数据属性 . 2)事件“click”的处理程序无效:未定义

有人可以帮我吗?

1 回答

  • 1

    从孩子到父母的发出(see this post to understand):

    Vue.component('vue-form-input', {
      props: {
        initName: { type: String },
        placeholder: {
          type: String,
          required: true
        }
      },
      data: function() {
        return {
          name: this.initName
        }
      },
      template:`
        <div>
            <input v-model="name" type="text" class="form-control" :placeholder="placeholder">
        </div>`,
      watch: {
        name: function() {
          this.$emit('change', this.name);
        }
     }
    });   
    
    Vue.component('vue-form-submit', {
      props: {
          buttonText: {
              String,
              required: true,
              default: 'Submit' }
    
      },
      template:`
          <div>
              <button v-on:click="submitBut" class="btn btn-lg btn-primary btn-block" type="submit">{{buttonText}}</button>
          </div>`,
          
      methods: {
        submitBut: function() {
          this.$emit('submit');
        }
      }
    });
    
    
    new Vue({
      el: '#forms',
      data: {
    		name: ''
      },
      methods: {
        changeInput: function(name) {
          this.name = name;
        },
        submitBut: function() {
          alert(this.name);
        }
      }
    })
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.js"></script>
    
    
    <div id="forms">
    
      <vue-form-input @change="changeInput" :init-name="name" placeholder="Name"></vue-form-input>
      <vue-form-submit @submit="submitBut" button-text="Submit"></vue-form-submit>
      Parent : {{ name }}
        
    </div>
    

相关问题