[英]VueJs 2: How to use one component function in another component?
我有 2 個組件,需要使用 function 和組件 B 中組件 A 的道具。function 只是隱藏/顯示 HTML 元素。 但是,它不能正常工作。
我的設置組件:
Vue.component('settings', {
props: {
settingsContainer: {
type: String,
required: true
}
},
template: `
<div>
<button @click="toggleOverlay">Settings</button>
</div>
`,
methods: {
toggleOverlay: function() {
if (this.settingsContainer === 'block') {
this.settingsContainer = 'none';
}else if (this.settingsContainer === 'none') {
this.settingsContainer = 'block';
}
console.log(this.settingsContainer);
return this.settingsContainer;
}
}
});
我使用它的組件:
Vue.component('sample-comp', {
template: `
<div>
<settings
:settings-container="displaySettings"
></settings>
<div :style="{ display: displaySettings }">
<p>Some Text</p>
</div>
</div>
`,
data: function() {
return {
displaySettings: 'block' //toggleOverlay should change its value
};
}
});
主應用:
new Vue({
el: '#app'
});
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12" defer></script>
<!-- <script src="https://unpkg.com/vue@next" defer></script> -->
<script src="test-settings-bt.js" defer></script>
</head>
<body>
<section id="app">
<sample-comp></sample-comp>
</section>
</body>
</html>
我在控制台中看到 toggleOverlay 會更改值,但不會影響我的樣式(不會更改 displaySettings 值)。
我建議使用事件或 Vuex 存儲來傳遞設置值(僅當這是更大更復雜的應用程序的一部分並且設置有其他影響時才使用 Vuex 存儲)。
更好的做法是為組件定義明確的 API 並讓組件本身處理其外觀,而不是直接在組件 Y 中更改組件 X 的外觀。
此外,正如 Phil 在評論中指出的那樣,您永遠不應該更改道具。 它們應作為只讀方式處理。
這是您可以執行的操作:
settings
組件中發出一個事件。 要么有兩個事件,一個用於顯示覆蓋,另一個用於隱藏它或僅使用 boolean 有效負載發出一個事件。sample-comp
上的事件/事件並相應地更改您的 css 屬性。親切的問候。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.