简体   繁体   中英

Vue.js component not working

I can't seem to figure out how to make components work. Without the component it works fine (the commented code).

Here's my HTML:

<strong>Total Price:</strong> <span v-text="total"></span><br>
<strong>CPC:</strong> <span v-text="cpc"></span>

Here's my Vue.js code:

Vue.component('my-component', {
    // data: function() {
    //     return { interval: 0, exposure: 0, clicks: 0, total: 0, cpc: 0 }
    // },
    computed: {
        total: function () {
            return(this.clicks * (this.exposure * 0.001 / 10) / 700).toFixed(8)
        },
        cpc: function () {
            return((this.total) / (this.clicks > 0 ? this.clicks : 1)).toFixed(8)
        }
    }
});

const app = new Vue({
    el: '#app',
    data: {
        interval: 0, exposure: 0, clicks: 0, total: 0, cpc: 0
    },
    // computed: {
    //     total: function () {
    //         return(this.clicks * (this.exposure * 0.001 / 10) / 700).toFixed(8)
    //     },
    //     cpc: function () {
    //         return((this.total) / (this.clicks > 0 ? this.clicks : 1)).toFixed(8)
    //     }
    // }
});

1) This doesn't work unless I uncomment the commented code.

2) JSFiddle: http://jsfiddle.net/tjkbf71h/3/

You didn't define the template for your component, so Vue doesn't know where and how to render your component.

You can go with inline template strings, mount it to template tag, or go with Single File Components - with webpack or browserify.

First, I suggest you to read docs

https://v2.vuejs.org/v2/guide/components.html

You need to include the component in your HTML markup:

<div id="app">
    <my-component></my-component>
</div>

And then the HTML you want displayed as part of this component needs to be in a template, inline or otherwise:

Vue.component('my-component', {
    template: '<div>Your HTML here</div>',
    data: function() {
         return { interval: 0, exposure: 0, clicks: 0, total: 0, cpc: 0 }
    },
//

Maybe you want to use single file component if you think it's ugly. https://v2.vuejs.org/v2/guide/single-file-components.html

its a syntax error in object remove comma from last item of object and your code will run normally删除红色标记的逗号

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM