javascript - 请问vue 子组件模板 怎么用父组件传递的html字符串?
阿神
阿神 2017-04-11 13:14:47
[JavaScript讨论组]

请问vue 子组件模板 怎么用父组件传递的html字符串?
父组件要传递一段html到子组件。
下面的写法报错 Component template requires a root element, rather than just text。

var vm=new Vue({ el:"#app", data:{ temp:"

1234

" }, components:{ "comp":{ template:'this.temp', props:['temp'] }} })
阿神
阿神

闭关修行中......

全部回复(5)
PHPz

最后使用 函数化组件(支持webpack)实现了需求.

<p id="app">
    <child :para="this.argus" :temp="this.html"></child>
</p>
<script>
   var vm = new Vue({
    el: "#app",
    data: {
        html: `<input>`,
        argus: {type: 'text'}
    },
    components: {
        child: {
            functional: true,
            render:(h, context)=> {
                const temp = context.props.temp;
                const para = context.props.para;
                return h({template: temp}, {
                    attrs: para
                })
            },
            props: {
                temp: {
                    type: String,
                    required: true
                },
                para: {
                    type: Object,
                    required: true
                }
            }
        }
    }
})
</script>
迷茫
template:'this.temp',

这里应该去掉单引号

天蓬老师

应该不可以吧,组件模板要先编译成 render 函数再使用的

你可以考虑写成 render 函数,在 render 函数里接受父组件传来的参数,实现可变组件,但直接接受父组件的 html 串作为模板应该是不可行的

天蓬老师
template: <p v-html='temp'></p>
怪我咯

谢邀
首先,如果你是单纯的传递一段静态的html代码。@zWìng 的做法已经可以了。
但如你要传递动态的template:'<p>123{{name}}</p>',我建议别这样用。
如果你有需要动态替换内容区域的需求,你可以参考官方的动态组件

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号