我试图创建一个可重复使用的Knockout.js组件,但是当我加载html页面时,在控制台“无法解析绑定”中看到以下错误
<script type="text/javascript">
var loginComponentViewModel = function(params){
this.UserName = params.UserName;
this.Password = params.Password
}
ko.components.register('login-component',{
viewModel: loginComponentViewModel,
template:{element:'login-templ'}
})
ko.applyBindings();
</script>
<!DOCTYPE html>
<head>
<script src='knockout-3.4.2.js'></script>
</head>
<body>
<div data-bind="component:{
name: 'login-component',
params: {UserName:'U1',Password:'1234'}
}"></div>
<login-component params="UserName:'U2',Password:'4321"></login-component>
<template id='login-templ'>
UserName <input type="text" name="txtUserName" data-bind="value:UserName"><br>
Password <input type="text" name="txtPassword" data-bind="value:Password"><br>
</template>
</body>
答案 0 :(得分:0)
一个非常小的错误。使用组件时,请交换使用双引号和单引号。
您必须使用"UserName:'U2',Password:'4321'"
代替'UserName:"U2",Password:"4321"'
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="component:{
name: 'login-component',
params: {UserName:'U1',Password:'1234'}
}"></div>
<login-component params='UserName:"U2",Password:"4321"'></login-component>
<template id='login-templ'>
UserName <input type="text" name="txtUserName" data-bind="value:UserName"><br>
Password <input type="text" name="txtPassword" data-bind="value:Password"><br>
</template>
<script type="text/javascript">
var loginComponentViewModel = function(params){
this.UserName = params.UserName;
this.Password = params.Password
}
ko.components.register('login-component',{
viewModel: loginComponentViewModel,
template:{element:'login-templ'}
})
ko.applyBindings();
</script>