【问题标题】:Using Vue components with props使用带有 props 的 Vue 组件
【发布时间】:2022-02-08 13:30:22
【问题描述】:

我正在上 Vue 学校课程,我正在尝试使用组件和道具做一些练习。我正在尝试构建一个简单的按钮和段落组件,它将段落的内容作为道具的值:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Click-Counter</title>
</head>
<body>
    <div id="app">
        <h1>Vue.js Components Fundamentals</h1>
        <click-counter click-title="The first counter is:"></click-counter>
        <click-counter click-title="The second counter is:"></click-counter>
        <click-counter click-title="The Third counter is:"></click-counter>
    </div>

    <script type="text/x-template" id="click-counter-template">
        <div>
            <p>{{ click-title }}</p>
            <button v-on:click="count++"> {{ count }} </button>
        </div>
    </script>

    <script src="https://unpkg.com/vue"></script>
    <script src="app.js"></script>
</body>
</html>

app.js

Vue.component('click-counter', {
    props: {
        'click-title': {
            type: String,
            required: true
        }
    },
    data () {
      return {
        count: 0
      }
    },
    template: '#click-counter-template',
})

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

问题是 click-title 道具的内容正在评估但未呈现。

Vue 扩展的屏幕截图

页面内容的屏幕截图

【问题讨论】:

    标签: javascript html vue.js


    【解决方案1】:

    问题在于,为了让 Vue 理解 app.js 文件和 index.html 文件中的 prop 是同一件事,您必须在 app.js 中使用 camelCase(并且当您定义组件时)和 index.html 中的 kebab-case(在组件的实例中)。

    简而言之,我改变了这个:

    index.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <!-- Some Head Info -->
    </head>
    <body>
        <div id="app">
            <h1>Vue.js Components Fundamentals</h1>
            <!-- USE kebab-case HERE (click-title) -->
            <click-counter click-title="The first counter is:"></click-counter>
            <click-counter click-title="The second counter is:"></click-counter>
            <click-counter click-title="The Third counter is:"></click-counter>
        </div>
    
        <script type="text/x-template" id="click-counter-template">
            <div>
                <!-- USE camelCase HERE (clickTitle) -->
                <p>{{ clickTitle }}</p>
                <button v-on:click="count++"> {{ count }} </button>
            </div>
        </script>
        
        <!-- More stuff -->
    </body>
    </html>
    

    app.js:

    Vue.component('click-counter', {
        props: {
            // USE camelCase HERE (clickTitle)
            'clickTitle': {
                // Atributes
            }
        },
        data () {
          // Variables
        },
        // Template
    })
    
    // New Vue
    

    【讨论】:

      猜你喜欢
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      • 2017-11-20
      • 2019-07-16
      • 2017-11-08
      • 2020-08-26
      • 2017-11-08
      • 2018-04-23
      相关资源
      最近更新 更多