模板内容未注入插槽



我试图使用slots将内容从父组件注入到其子组件,但Vue一直呈现默认内容,而不是解析从其父组件发送的内容。

这是父组件的代码,而父组件又是全局组件的子组件:

let parentComponent = {
template: `
<div>
<child-component>
<template v-slot:action>Close</template>
<template v-slot:element>Modal</template>
</child-component>
</div>        
`,
components: {
'child-component': childComponent 
}
};

这里是它的子组件,我想在这里传递内容:

let childComponent = {
template: `
<button>
<slot name="action">Open</slot>
<slot name="element">Window</slot>
</button>       
`,
};

按钮仍然显示默认内容:"打开窗口">

我做错了什么?

编辑:

这是剩下的内容,以防万一有帮助:

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>VueJS</title>
</head>
<body>
<div id="app">
<vue-directives></vue-directives>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script src="components/slotDirective/slotDirectiveSubcomponent.js"></script>
<script src="components/slotDirective/slotDirective.js"></script>
<script src="components/VueDirectives.js"></script>
<script>
let vue = new Vue({
el: '#app'
});
</script>
</body>
</html>

和VueDirectives.js:

Vue.component('vue-directives', {
template: `
<div>
<h3>{{ title }}</h3>
<parentComponent/>
</div>
`,
data() {
return {
title: "VueJS directives",
}
},
components: {
parentComponent 
}
});
我修复了这个错误。我不知道原因,但如果我从CDN加载Vue.js,或者我在本地手动下载它,作为一个单独的文件,它都不起作用。

然后,我终于尝试从npm安装它,并在node_modules/vue/dist/vue.js中加载Vue.js,这样它就可以工作了。我认为Vue.js不符合它的所有功能。

我不确定插槽是否是为此而设计的。如果你只是更改一个按钮的文本,将道具传递到parentComponent中,我会这样做。例如

<parentComponent buttonText="some text or bind with a data value or computed prop"/>

请参阅:https://v2.vuejs.org/v2/guide/components-props.html

正在使用插槽。。。如果你正在尝试这个,一个可重复使用的对话框,你可以在任何地方弹出并控制内容。例如

// myDialog
<v-dialog>
<slot>Here you can put what you want</slot>
</v-dialog>

使用:

<myDialog>
<template>
<myContent /> Or just put content here without another component
</template>
</myDialog>

最新更新