2017-08-21 27 views
1

我已將vue 1.0.18 min.js包含在html頁面的腳本標記中。Vue 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給出定義。

this.parent.blockVal給出未定義。

this.chars[0].blockVal說明字符是未定義的。

tagApp.chars[0].blockVal說tagApp是未定義的。

請幫忙。

回答

-2

您無法直接在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。您可以嘗試附加其他生命週期掛鉤取決於您的要求

+1

這工作。謝謝!但是,當我改變blockVal,specialText仍然使用舊的blockVal值,因爲創建只調用一次。所以我添加了一個方法來更新specialText,它的工作原理。 – MathewT

+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

好的。謝謝。我現在在應用程序外部定義了blockVal並將其包含在specialText中。這工作。 – MathewT

相關問題