Svelte踩坑日记:Input value双向绑定后不能动态指定type

1,277 阅读1分钟

最近在开发过程中需要编写了一个input组件,外部监听事件,根据双向绑定的value进行事件监听,然后发现一个问题。


组件原本代码:

<script>
  export let type= "text";
  export let value = "";
</script>

<input
  on:keyup
  on:change
  {type}
  bind:value />

外部调用:

<script>
	import Input from "./Input.svelte";
	let value = "";
	let text = "";
	function Foo(){
		if(value.length < 4){
			text="密码长度过短!";
		}else{
			text="";
		}
	}
</script>

<Input bind:value type='password' on:change={Foo}/>
<p>{text}</p>


但是这么写编译阶段会报错:'type' attribute cannot be dynamic if input uses two-way binding (Input.svelte:9:1)

去github下查了一下,发现是编译器本身禁用了这种操作:github.com/sveltejs/sv…


好像是原本这么写会存在gotcha(坑),不管了,找个折中的办法吧,既然不能直接指定,那么间接指定吧。

思路:组件内部绑定其element,然后根据其element指定type,然后外部传入一个别名的type。



OK,上代码:


组件内部:

<script>
  import { onMount } from "svelte";
	
  export let inputType= "text";
  export let value = "";
	
  let inputElement;
  onMount(() => {
    inputElement.type = inputType;
  });
</script>

<input
  on:keyup
  on:change
  bind:value 
  bind:this={inputElement}/>

外部调用:

<script>
	import Input from "./Input.svelte";
	let value = "";
	let text = "";
	function foo(){
		if(value.length < 4){
			text="密码长度过短!";
		}else{
			text="";
		}
	}
</script>

<Input bind:value inputType='password' on:change={foo}/>
<p>{text}</p>


OK,大功告成!