Vue js应用程序未在应用程序内定义

时间:2017-08-21 16:45:52

标签: javascript vue.js undefined

我在vtml页面的脚本标记中包含了vue 1.0.18 min.js.

specialText行不起作用。

var tagApp;

window.onload = function () {
    /* Vue Js App here */
tagApp = new Vue({
  el: '#app',
  data: {
    title: 'Title',
    chars: [{
        name: "Jarred",
        attack: 15,
        health: 70,
        special: "Block",
        blockVal: 5,
        specialText: "Passive: Blocks "+ tagApp.chars[0].blockVal +" Damage." 
    // line above: here it doesn't work
    // gives: "can't get chars of undefined"
        }, {
            name: "John"
        }]
     } 
}); // close app
alert(tagApp.chars[0].blockVal); // here it works
getBlockVal(); // here it also works

} // close window.onload

function getBlockVal() {
    var arr = [{
        name: "henry",
        description: "blocks " + tagApp.chars[0].blockVal + " dmg."
    }];
    alert(arr[0].description);
}

我也在specialText中尝试了以下内容:

this.blockVal给出了undefined。

this.parent.blockVal给出了undefined。

this.chars[0].blockVal说字符未定义。

tagApp.chars[0].blockVal表示tagApp未定义。

请帮忙。

2 个答案:

答案 0 :(得分:0)

您不能在其定义中使用tagApp.chars个对象,这就是未定义的原因。从字符定义中删除行tagApp.chars[0].blockVal,一切都会起作用。 “如果仍需要定义变量值,则无法使用变量值。”

如果您运行以下代码,则可以运行:

var tagApp;

window.onload = function () {
    /* Vue Js App here */
tagApp = new Vue({
  el: '#app',
  data: {
    title: 'Title',
    chars: [{
        name: "Jarred",
        attack: 15,
        health: 70,
        special: "Block",
        blockVal: 5,
        specialText: "Passive: Blocks " + " Damage." 
    // line above: here it doesn't work
    // gives: "can't get chars of undefined"
        }, {
            name: "John"
        }]
     } 
}); // close app
alert(tagApp.chars[0].blockVal); // here it works
getBlockVal(); // here it also works

} // close window.onload

function getBlockVal() {
    var arr = [{
        name: "henry",
        description: "blocks " + tagApp.chars[0].blockVal + " dmg."
    }];
    alert(arr[0].description);
}

答案 1 :(得分:-1)

您无法直接在data属性中更新值。使用created生命周期钩子方法来更新数据对象,

created: function(){
   this.chars[0].specialText = "Passive: Blocks "+ this.chars[0].blockVal +" Damage."
}

关于Vue.js v1生命周期钩子,https://v1.vuejs.org/guide/instance.html#Lifecycle-Diagram。您可以尝试附加其他生命周期钩子取决于您的要求